﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using RightClickExtension.Properties;

namespace RightClickExtension
{
    public partial class frmMain : Form
    {
        #region Instance fields

        private string _targetStartFolder;
        private string _sourcePath;
        private string _targetFolder;
        private char _sapertor = '/';
        private char _allowSapertor = '-';
        private readonly bool _modeMove;
        private string _formatDate = "dd-mm-yyyy HH:mm:ss";

        #endregion

        #region .ctors

        public frmMain(string[] args)
        {
            InitializeComponent();
            lblPath.Text = _targetStartFolder = Settings.Default.TargetPath;
            if (args.Length == 2)
            {
                _sourcePath = args[0];
                if (args[1] == "M")
                    _modeMove = true;
                else if (args[1] == "C")
                    _modeMove = false;
                else
                    return;

            }
            else
            {
                MessageBox.Show(Resources.ErrorParamters);
            }

        }
        #endregion

        #region Instance methods

        /// <summary>
        /// Processes the file.
        /// </summary>
        private void ProcessFile()
        {
            if (CheckInput())
            {
                bool cancelAction = false;
                string targetPath = Path.Combine(_targetStartFolder, _targetFolder);
                if (!Directory.Exists(targetPath))
                {
                    frmExist exsitDirtory = new frmExist();
                    exsitDirtory.TargetFileName = _targetFolder;
                    exsitDirtory.ShowDialog();
                    if (exsitDirtory.Result)
                    {

                        _targetFolder = exsitDirtory.TargetFileName;
                        targetPath = Path.Combine(_targetStartFolder, _targetFolder);
                        Directory.CreateDirectory(targetPath);
                    }
                    else
                        cancelAction = true;

                }
                if (!cancelAction)
                {
                    FileInfo fi = new FileInfo(_sourcePath);
                    string newFileLocationPath = Path.Combine(targetPath, fi.Name);
                    if (File.Exists(newFileLocationPath))
                    {
                        frmExist exsitFile = new frmExist();
                        exsitFile.ExistFile = true;
                        exsitFile.TargetFileName = fi.Name;
                        exsitFile.ShowDialog();
                        if (exsitFile.Result)
                        {
                            newFileLocationPath = Path.Combine(targetPath, exsitFile.TargetFileName);
                        }
                        else
                            cancelAction = true;
                    }

                    if (!cancelAction)
                    {
                        try
                        {
                            if (_modeMove)
                            {
                                fi.MoveTo(newFileLocationPath);
                                Helper.WriteActionToLog(string.Format(Resources.strMoveFormat, _sourcePath, newFileLocationPath, DateTime.Now.ToString(_formatDate)));
                            }
                            else
                            {
                                fi.CopyTo(newFileLocationPath);
                                Helper.WriteActionToLog(string.Format(Resources.strCopyFormat, _sourcePath, newFileLocationPath, DateTime.Now.ToString(_formatDate)));
                            }
                            if (cbEmail.Checked)
                                Helper.SendFileByEmail(newFileLocationPath,fi.Name);

                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(Resources.ErrorCopyMove);
                            Helper.WriteToErrorLog(ex, Resources.ErrorCopyMove);
                        }
                        finally
                        {
                            Application.Exit();
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Checks the input.
        /// </summary>
        /// <returns></returns>
        private bool CheckInput()
        {
            bool result = false;
            epFolderNumber.Clear();
            if (!string.IsNullOrEmpty(tbFileFolder.Text))
            {
                string fileName = tbFileFolder.Text;
                if (fileName.StartsWith(_sapertor.ToString()))
                {
                    epFolderNumber.SetIconPadding(tbFileFolder, -18);
                    epFolderNumber.SetError(tbFileFolder,Resources.ErrorFileNumberChar);
                }
                else if (!fileName.Contains(_sapertor.ToString()))
                {
                    epFolderNumber.SetIconPadding(tbFileFolder, -18);
                    epFolderNumber.SetError(tbFileFolder, Resources.ErrorFileNumbersLessTwo);
                }
                else
                {
                    string[] fileNumber = fileName.Split(_sapertor);
                    if (fileNumber.Length < 2 && fileNumber.Length <= 3)
                    {
                        epFolderNumber.SetIconPadding(tbFileFolder, -18);
                        epFolderNumber.SetError(tbFileFolder, Resources.ErrorFileNumbersLessTwo);
                    }
                    else
                    {
                        bool validFolderNumber = true;
                        foreach (string s in fileNumber)
                        {
                            int number;
                            validFolderNumber = int.TryParse(s, out number);
                        }
                        if (validFolderNumber)
                        {
                            _targetFolder = fileName.Replace(_sapertor, _allowSapertor);
                            result = true;
                        }
                        else
                        {
                            epFolderNumber.SetIconPadding(tbFileFolder, -18);
                            epFolderNumber.SetError(tbFileFolder, Resources.ErrorFileNumberIncorrect);
                        }
                    }
                }

            }
            else
            {
                btnGo.Enabled = false;
                epFolderNumber.SetIconPadding(tbFileFolder, -18);
                epFolderNumber.SetError(tbFileFolder, Resources.ErrorEmpty);
            }
            return result;
        }
        #endregion

        #region Auxiliary methods

        private void btnGo_Click(object sender, EventArgs e)
        {
            ProcessFile();
        }       

        private void tbFileFolder_Leave(object sender, EventArgs e)
        {
            epFolderNumber.Clear();
            if (!string.IsNullOrEmpty(tbFileFolder.Text))
            {
                string fileName = tbFileFolder.Text;
                if (fileName.Contains(_sapertor.ToString()))
                {
                    fileName = fileName.Replace(_sapertor, _allowSapertor);
                    lblPath.Text = string.Format("{0}\\{1}", lblPath.Text = Settings.Default.TargetPath, fileName);
                    btnGo.Enabled = true;
                }
            }
            else
            {
                btnGo.Enabled = false;
                epFolderNumber.SetIconPadding(tbFileFolder, -18);
                epFolderNumber.SetError(tbFileFolder, Resources.ErrorEmpty);
            }

        }

        private void tbFileFolder_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
            { e.Handled = false; }
            else if (System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), _sapertor.ToString()))
                e.Handled = false;
            else if (e.KeyChar == 8)
                e.Handled = false;
            else if (e.KeyChar == 13)
                ProcessFile();
            else
                e.Handled = true;

        }

        private void llClose_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Close();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            Point x = Cursor.Position;
            Point cursor = Cursor.Position;

            if (cursor.X + this.Width > Screen.PrimaryScreen.Bounds.Width)
                x.X = Screen.PrimaryScreen.Bounds.Width - this.Width ;
            if (cursor.Y + this.Height > Screen.PrimaryScreen.Bounds.Height)
                x.Y = Screen.PrimaryScreen.Bounds.Height -this.Height ;
            this.Location = x;
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            tbFileFolder.Text = string.Empty;
            lblPath.Text = _targetStartFolder = Settings.Default.TargetPath;
        }

        #endregion

    }
}
